package com.chengliang.bbs.filter;

import com.chengliang.bbs.exception.ValidateCodeException;
import com.wf.captcha.utils.CaptchaUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.thymeleaf.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.chengliang.bbs.util.StringUtil.CODE_NAME;

/**
 * @Author chengliang
 * @Date 2019-06-12 21:14
 * @Description //TODO
 * 登录验证码过滤器
 */
@Slf4j
@Component
public class ValidateCodeFilter extends OncePerRequestFilter {

    /**
     * 登录地址名称
     */
    @Value("${security.login-url}")
    private String loginPath="/user/login";

    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        if(StringUtils.equals(loginPath, httpServletRequest.getRequestURI())
                && StringUtils.equalsIgnoreCase(httpServletRequest.getMethod(), "post")) {
                // 1. 进行验证码的校验
                if (!CaptchaUtil.ver(httpServletRequest.getParameter(CODE_NAME), httpServletRequest)) {
                    // 2. 如果校验不通过，调用SpringSecurity的校验失败处理器
                    authenticationFailureHandler.onAuthenticationFailure(httpServletRequest
                            ,httpServletResponse
                            ,new ValidateCodeException("验证码效验失败"));
                    return;
                }
        }
        // 3. 校验通过，就放行
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }


}
